<script lang="ts" setup>
import { useUserStore } from "@/stores";
const store = useUserStore();

import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
import {loginAIP} from "@/api/user"

import { useRouter } from "vue-router"

const router = useRouter()

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('Please input the password'))
  } else {
    if (ruleForm.value.password !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('password', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('Please input the password again'))
  } else if (value !== ruleForm.value.password) {
    callback(new Error("Two inputs don't match!"))
  } else {
    callback()
  }
}

const ruleForm = ref({
  username: '',
  password: '',

})

const rules = reactive({
  username: [{ validator: validatePass, trigger: 'blur' }],
  password: [{ validator: validatePass2, trigger: 'blur' }],
 
})

const submitForm =  (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid:any) => {
    if (valid) {
      const res = await loginAIP(ruleForm.value)
      store.setToken(res.data.token)
      
      ElMessage({
    showClose: true,
    message: '登录成功',
    type: 'success',
    duration: 0,
      })
  router.push('/')
      
    } else {
      console.log('error submit!')
      return false
    }
  })
}


</script>

<template>
  <div class="login">
    <div class="login-new">
      <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="ruleForm.username"  autocomplete="off" />
    </el-form-item>
   
    <el-form-item label="密码" prop="password">
      <el-input v-model.number="ruleForm.password"  type="password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >Submit</el-button
      >
    
    </el-form-item>
  </el-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background: url('../../asster/image/8eb342d9ac03f3fc729aa2716ca11dde.jpg');
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover; /* 或者 'contain' */
}
.login-new {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 500px;
  height: 300px;
  background-color: #fff;
}
:deep .el-form {
  width: 400px;
}
:deep .el-button--primary {
  width: 200px;
}
</style>
